<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
	<view class="create-invoice">
		<!-- 这里设置了z-paging加载时禁止自动调用reload方法，自行控制何时reload（懒加载）-->
		<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
		<z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" :auto="true">
			<template #top>
				<view class="" style="background-color: #FFFFFF;">
					<u-navbar :border-bottom="false" title="生成发票单" :title-size="36" :title-bold="true" :title-color="textColor">
					</u-navbar>
				</view>	
			</template>
			
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
			<view class="payorder-container" >
					<u-checkbox-group :wrap="true" :size="40" :icon-size="20" :label-disabled="true" shape="circle" :active-color="themeColor" @change="checkboxGroupChange">
						<u-checkbox
							v-model="item.isSelect" 
							v-for="item in dataList" :key="item.id" 
							:name="JSON.stringify(item)"
							class="check-container"
							@change="checkItemChange"
						>
							<view class="payorder-section">	
								<view class="section-list">
									<view class="section-item">
										<view class="section-item-text">
											<view class="section-item-name">
												{{item.tradeNo}}
											</view>
											<view class="section-item-status">
												<text style="font-size: 24rpx;color: #999999;">{{$u.timeFormat(item.createdTime,'yyyy-mm-dd hh:MM')}}</text>
												<text style="font-size: 24rpx;color: #FF551A;margin-left: 30rpx;">{{orderStatus[item.state]}}</text>
											</view>
										</view>
										<view class="text-bold badge-color u-font-32">
											￥{{item.actualAmount}}
										</view>
									</view>
								</view>
							</view>
						</u-checkbox>
					</u-checkbox-group>
			</view>
			<template #bottom>
					<view class="create-footer" >
						<u-checkbox v-model="allChecked" :size="40" :icon-size="20" shape="circle" :active-color="themeColor">全选</u-checkbox>
						<view class="create-footer-rt">
							<view class="create-footer-total">
								合计：<text style="font-size: 32rpx;
							font-weight: bold;
							color: #FF551A;">{{totalPrice}}</text>
							</view>
							<view class="create-footer-btn" @click="openCreatePop">
								创建发票单
							</view>
						</view>
					</view>
			</template>
			
		</z-paging>
		<u-toast ref="uToast" />
		<u-popup v-model="createInvoiceShow" mode="bottom" safe-area-inset-bottom class="create-invoice-pop"	>
			<view style="min-height: 1200rpx;" class="u-p-l-35 u-p-r-35">
				<view class="u-text-center choose-buyer-title u-font-32" >
					创建发票单
				</view>
				<scroll-view scroll-y="true" style="height: 1000rpx;">
					<view >
						<view class="u-flex u-p-b-30" style="border-bottom: 1rpx solid #E7E7E7;">
							<view class="text-bold u-font-30 u-m-r-40">开票方式</view>
							<u-radio-group v-model="invoiceType">
								<u-radio label-size="26" active-color="#ffbb1a"	:name="0" class="u-font-26">增值税普通发票</u-radio>
								<u-radio label-size="26" active-color="#ffbb1a" :name="1">增值税专用发票</u-radio>
							</u-radio-group>
						</view>
						<view class="u-p-t-30 u-p-b-30" style="border-bottom: 1rpx solid #E7E7E7;">
							<view v-if="!invoiceInfoLoading">
								<view class="" v-if="!loadInvoice">
									<view class="text-bold u-font-30 u-m-r-40">发票信息</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">名称</view>
										<view class="invoice-text u-font-28">{{invoiceData.name}}</view>
									</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">纳税人识别号 </view>
										<view class="invoice-text u-font-28">{{invoiceData.identityNo}}</view>
									</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">地址 </view>
										<view class="invoice-text u-font-28">{{invoiceData.address}}</view>
									</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">电话 </view>
										<view class="invoice-text u-font-28">{{invoiceData.telNo}}</view>
									</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">开户行 </view>
										<view class="invoice-text u-font-28">{{invoiceData.bankName}}</view>
									</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">银行账号 </view>
										<view class="invoice-text u-font-28">{{invoiceData.accountNo}}</view>
									</view>
									<view class="u-flex u-col-top u-m-t-20">
										<view class="invoice-title grey-color u-font-28">发票邮寄地址 </view>
										<view class="invoice-text  u-font-28" v-if="!editAddress">
											<text class="u-m-r-10">{{deliveryAddress}}</text>
											<text  @click="editAddress = true;" class="badge-color">{{deliveryAddress?'修改':'立即配置'}} <u-icon name="edit-pen" color="#ff551a"></u-icon></text>
												
										</view>
										<view class="invoice-text" v-else>
											<u-input v-model="deliveryAddress" type="textarea" border/>
											<u-button size="mini" class="u-m-t-20" @click="editAddressConfirm()">确定</u-button>
										</view>
									</view>
								</view>
								<view class="u-flex u-row-center" v-else style="height: 500rpx;flex-direction: column;">
									<image src="../../../static/home/noMore.png" mode="widthFix" style="width: 200rpx;"></image>
									<view class="u-text-center u-m-10">获取发票配置信息失败~ </view>
									<view class="u-text-center badge-color" @click="getInvoiceInfoByBuyer()">点击重新获取 </view>
								</view>
							</view>
							<view class="u-flex u-row-center" v-else style="height: 500rpx;">
								<u-loading mode="circle" size="40" color="#ff551a"></u-loading>
							</view>
						</view>
						<view class="u-p-t-30">
							<view class="text-bold u-font-30 u-m-r-40 u-m-b-30">已选订单{{this.chooseOrderList.length}}个</view>
							<view class="u-flex u-row-between u-m-b-30" v-for="(item,index) in chooseOrderList" :key="index">
								<view class="u-flex">
									<view>
										<image src="/static/order/payorderDel.png" mode="widthFix" style="width: 32rpx;height: 32rpx;"  class="u-m-r-30" @click.stop="delOrderFn(index)"></image>
									</view>
									<view class="">
										<view class="text-bold u-font-30">
											{{JSON.parse(item).tradeNo}}
										</view>
										<view>
											<text style="font-size: 24rpx;color: #999999;">{{$u.timeFormat(JSON.parse(item).createdTime,'yyyy-mm-dd hh:MM')}}</text>
											<text style="font-size: 24rpx;color: #FF551A;margin-left: 30rpx;">{{orderStatus[JSON.parse(item).state]}}</text>
										</view>
									</view>
								</view>
								<view class="text-bold badge-color u-font-32">
									￥{{JSON.parse(item).actualAmount}}
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="u-m-t-40 u-m-b-20" style="background-color: #fff;">
					<u-button  @click="creatdPayOrderFn" plain shape="circle" 
					:hair-line="false" hover-class="none" :custom-style="{background:'#ffbb1a',border:'none'}" >确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import { useShopStore } from '@/store/shop.js';
	import { mapState } from 'pinia';
	export default {
		data() {
			return {
				editAddress:false,
				loadInvoice:false,
				invoiceInfoLoading:false,
				invoiceData:{},
				invoiceType:0,
				createInvoiceShow:false,
				buyerShow:false,
				chooseShopTitle:'',
				chooseShopId:'',
				dataList: [],
				chooseOrderList:[],
				allChecked:false,
				shopId:'',
				orderStatus:['待确认','待发货','待收货','待评价','已完成','已取消'],
				deliveryAddress:'',
			}
		},
		onLoad(options) {
				this.shopId = options.shop;
				this.chooseShopId = options.shop;
				this.chooseShopTitle = options.name;
		},
		computed:{
			...mapState(useShopStore, {storeShop: 'shop'}),
			totalPrice(){
				let total = 0;
				let that = this;
				this.dataList.forEach(item=>{
					if(item.isSelect){
						total = that.addFn(total,item.actualAmount)
					}
				})
				return '￥'+total;
			}
		},
		watch:{
			allChecked(val,oldval){
				let ary = [];
				this.dataList.forEach(item=>{
					item.isSelect = val;
					// ary.push(item.id);
					if(val){
						ary.push(JSON.stringify(item));
					}					
				});
				this.chooseOrderList = ary;
			}
		},
		methods: {
			delOrderFn(index){
				let delId = JSON.parse(this.chooseOrderList[index]).id;
				let _index = this.dataList.findIndex(item=>{return item.id === delId});
				this.$set(this.dataList[_index],'isSelect',false);
				this.chooseOrderList.splice(index,1);
			},
			editAddressConfirm(){
				if(!this.deliveryAddress){
					return this.$u.toast('发票邮寄地址不得为空！')
				}
				this.editAddress = false;
			},
			// 切换采购商，重置列表内容
			chooseBuyerFn(val){
				this.chooseShopId = val.id;
				this.chooseShopTitle = val.name;
				this.buyerShow = false;
				this.$refs.paging.reload();
				this.allChecked = false;
			},
			addFn(a,b){
			  return this.$mHelper.add(a,b)
			},
			checkItemChange(data){
				// console.log(val);
				
				console.log(this.chooseOrderList);
			},
			// 全选订单
			checkboxGroupChange(list){
				this.chooseOrderList = list;
			},
			// 打开新建发票单弹窗
			openCreatePop(){
				if(this.chooseOrderList.length===0){
					return this.$u.toast('您还没有选择订单~')
				}
				this.createInvoiceShow = true;
				this.getInvoiceInfoByBuyer()
			},
			// 获取买家发票信息
			async getInvoiceInfoByBuyer(){
				this.invoiceInfoLoading = true;
				this.loadInvoice = false;
				let params = {
					BuyerId:this.chooseShopId,
					SellerId:this.storeShop.id,
				}
				const res = await this.$newHttp.get('api/v1.3/Invoice/SellerGetBuyerInvoiceConfig', {params:params});
				this.invoiceInfoLoading = false;
				if(res.code === 200){
					this.invoiceData = res.data||{};
					this.deliveryAddress = this.invoiceData.deliveryAddress||'';
				}else{
					this.$u.toast(`获取${this.chooseShopTitle}的发票信息失败，错误信息：`+res.erroMessage);
					this.loadInvoice = true;
				}
			}, 
			// 创建发票单
			async creatdPayOrderFn(){
				uni.showLoading({
					title: 'loading...',
				});
				if(this.chooseOrderList.length === 0){
					uni.hideLoading({
						title: 'loading...'
					})
					this.$refs.uToast.show({
						title: '订单选择不得为空~',
						type: 'warning',
						position:'bottom'
					});
					return false;
				}
				if(!this.deliveryAddress){
					uni.hideLoading({
						title: 'loading...'
					})
					this.$refs.uToast.show({
						title: '邮寄地址不得为空~',
						type: 'warning',
						position:'bottom'
					});
					return false;
				}
				let ary = this.chooseOrderList.map(item=>{
					return JSON.parse(item).id;
				});
				let params = {
					tradeIds:ary,
					shopId:this.storeShop.id,
					sellerId:this.storeShop.id,
					buyerId:this.chooseShopId,
					isProfessional:Boolean(this.invoiceType),
					submit:false,
					deliveryAddress:this.deliveryAddress,
				}
				let res = await this.$newHttp.post('api/v1.3/Invoice/SellerCreateInvoice', params);
				uni.hideLoading({
					title: 'loading...'
				})
				if(res.code == 200){
						this.$mRouter.redirectTo({
							route: '/pages/sale/invoiceOrder/details?id='+res.data.id
						})
				}else{
					this.$refs.uToast.show({
						title: '创建发票单失败，失败原因：'+res.erroMessage,
						type: 'error',
						position:'bottom'
					});
				}
			},
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					ShopId:this.storeShop.id,
					
				}
				if(this.chooseShopId!=''){
					params.BuyerId = this.chooseShopId;
				}
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				const res = await this.$newHttp.get('api/v1.3/Invoice/SellerGetInvoiceTradesPage', { params: params } );
				console.log(res);
				uni.hideLoading({
					title: 'loading...'
				})
				if(res.code === 200){
					this.$refs.paging.complete(res.data.list);
				}else{
					this.$refs.paging.complete(false);
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.create-invoice {
		height: 100%;
		background-color: #f8f8f8;
		.select-container{
			border:2rpx solid #ffbb1a;
			border-radius:40rpx;	
			.choose-shop-title{
				flex:1;
				text-align: center;
				font-weight: bold;
				color:#333;
			}
			.no-shop{
				font-weight: normal;
				color:#999;
			}
		}
		.choose-buyer-title{
			position: relative;
			line-height: 100rpx;height: 100rpx;font-weight: bold;
			.clear-btn{
				position: absolute;
				right: 35rpx;
				top: 0;
				font-size: 28rpx;
				color: #ff551a;
			}
		}
		.create-invoice-pop{
			.invoice-title{
				width: 168rpx;
				overflow: hidden;
			}
			.invoice-text{
				flex:1;
				overflow: hidden;
				margin-left: 20rpx;
			}
			
		}
	}
	.payorder-container{
		background-color: #fff;
		box-sizing: border-box;
		padding: 0 35rpx;
		.check-container{
			::v-deep .u-checkbox__label{
				width: 100%;
			}
		}
		
		.payorder-header{
			display: flex;
			justify-content: space-between;
		}
		.payorder-section{
			display: flex;
			align-items: center;
			box-sizing: border-box;
			justify-content: space-between;
			align-items: center;
			padding:20rpx 0;
			border-bottom: solid 1px #eaeaea;
			.section-image{
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
			}
			.section-list{
				flex: 1;
				margin-left: 20rpx;
				
				.section-item{
					display: flex;
					width: 100%;
					justify-content: space-between;
					align-items: center;
					.section-btn{
						width: 100rpx;
						margin: 0;
						height: 50rpx;
					}
				}
			}
			
		}
		
	}
	
	.create-footer{
		box-sizing: border-box;
		padding: 30rpx 35rpx;
		background-color: #FFFFFF;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.create-footer-rt{
			display: flex;
			align-items: center;
			
			.create-footer-btn{
				background: linear-gradient(-90deg, #FFBB1A, #FFBB1A);
				box-sizing: border-box;
				padding:26rpx 42rpx;
				border-radius: 50rpx;
				color: #333;
				margin-left: 20rpx;
			}
		}
	}
</style>
